<?php
namespace app\store\controller\food;

use app\store\controller\food\Controller;
use app\store\model\UploadFile as UploadFileModel;
use hema\storage\Driver as StorageDriver;
use app\store\model\Setting as SettingModel;

/**
 * 文件库管理
 */
class Upload extends Controller
{
    private $config;

    /**
     * 构造方法
     */
    public function initialize()
    {
        parent::initialize();
        // 存储配置信息
        $this->config = SettingModel::getItem('storage',0);
    }

    /**
     * 图片上传接口
     */
    public function image($groupId = 0)
    {
        // 实例化存储驱动
        $storage = new StorageDriver($this->config);
        // 设置上传文件的信息
        $storage->setUploadFile('iFile')
            ->setValidationScene('image')
            ->upload();
        // 执行文件上传
        if (!$storage->upload()) {
            return $this->renderError('图片上传失败：' . $storage->getError());
        }
        // 文件信息
        $fileInfo = $storage->getSaveFileInfo();
        $fileInfo['group_id'] = $groupId;
        $fileInfo['file_type'] = 'image';
        // 添加文件库记录
        $model = new UploadFileModel;
        if($model->add($fileInfo)){
            $uploadFile = UploadFileModel::detail($model->file_id);
            // 图片上传成功
            die(json_encode(['code' => 1, 'msg' => '上传成功', 'data' => $uploadFile]));
        }
        die(json_encode(['code' => 0, 'msg' => '上传失败', 'data' => []]));
        
    }
}
